package csc.nndp.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.nndp.dao.User;
import csc.nndp.dao.UserDB;


/**
 * Servlet implementation class AddUser
 */
@WebServlet("/AddUser")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		
		
		String action = request.getParameter("action");
		List<String> messages = new ArrayList<String>();
		
		// In case of updating Employee
		if(action.equals("edit")){
			User e = new User(Integer.parseInt(request.getParameter("userId")),
					request.getParameter("userName"),
					
					request.getParameter("pass"),
					request.getParameter("firstName"),
					request.getParameter("lastName"),
					request.getParameter("Phone"),
					request.getParameter("email"),
					request.getParameter("role"));
					
			request.setAttribute("user", e);
			if("".equals(e.getFirstName()))
				messages.add("First Name is required field.");
			 
			if("".equals(e.getLastName()))
				messages.add("Last Name is required filed.");
			if(messages.size() > 0){
				request.setAttribute("messages", messages);
				RequestDispatcher dispatcher = request.getRequestDispatcher("editUser.jsp");
			    dispatcher.forward(request, response);
			}else{
				try {
					UserDB.updateUser(e);
					
					messages.add("Updated successfully.");
					request.setAttribute("messages", messages);
					RequestDispatcher dispatcher = request.getRequestDispatcher("view-user");
				    dispatcher.forward(request, response);
				} catch (Exception e1) {
					throw new ServletException(e1.getMessage());
				}
			}
			
		}else if(action.equals("confirm")){
			//List<String> messages = new ArrayList<String>();
			User e = new User(genUserId(),
					request.getParameter("userName"),
					request.getParameter("password"),
					request.getParameter("firstName"),
					request.getParameter("lastName"),
					request.getParameter("phone"),
					request.getParameter("email"),
					request.getParameter("role"));
			
			request.getSession().setAttribute("userInfo", e);
			
			if("".equals(e.getFirstName()))
				messages.add("First Name is required field.");
			 
			if("".equals(e.getLastName()))
				messages.add("Last Name is required filed.");
				
			if(messages.size() > 0){
				request.setAttribute("messages", messages);
				RequestDispatcher dispatcher = request.getRequestDispatcher("addUser.jsp");
			    dispatcher.forward(request, response);
			}else{
				//request.getSession().setAttribute("employeeInfo", e);
				RequestDispatcher dispatcher = request.getRequestDispatcher("userConfirm.jsp");
			    dispatcher.forward(request, response);
			}
			
		}else if(action.equals("add")){
			//List<String> messages = new ArrayList<String>();
			HttpSession session =  request.getSession();
			User e =(User) session.getAttribute("userInfo");
			if(e != null){
				try {
					UserDB.addUser(e);
					messages.add("Inserted successfully.");
				} catch (Exception e1) {
					throw new ServletException(e1.getMessage());
				}
				// Remove usser in Session scope after adding into the user List
				session.removeAttribute("userInfo");
				
				request.setAttribute("messages", messages);
				RequestDispatcher dispatcher = request.getRequestDispatcher("view-user");
			    dispatcher.forward(request, response);
		
			}else{
				throw new ServletException("user Not Found in Session scope any more.");
			}
		}

	}
	private int genUserId(){
		List<User> users;
		try {
			users = UserDB.getUserList();
			if(users != null && users.size() > 0){
				int id = users.get(0).getUserId();
				for(User e:users){
					if(e.getUserId() > id){
						id = e.getUserId();
					}
				}
				return id+1;
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		return 1;
	}

}
